package com.example.myspring.controller;

import com.example.myspring.entity.Student;
import com.example.myspring.service.CaptchaService;
import com.example.myspring.service.RedisService;
import com.example.myspring.service.StudentService;
import com.example.myspring.util.CaptchaUtil;
import com.example.myspring.util.ExcelServletUtil;
//import org.apache.ibatis.jdbc.Null;
//import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
//import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;


import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;

import java.util.Map;


@Controller
public class MyController {

    @Autowired
    private CaptchaService captchaService;

    @Autowired
    private StudentService ss;

    @Autowired
    private RedisService rs;

    //登录界面
    @RequestMapping("/index")
    public String index() {
        return "index"; // 返回的是index.html
    }

    //个人信息界面
    @RequestMapping("/home")
    public String home() {
        return "home"; // home.html
    }

    //上传文件界面
    @RequestMapping("/upload")
    public String upload() {
        return "upload"; // home.html
    }

    //处理文件至数据库
    @RequestMapping("/ExcelForMysql")
    public String ExcelForMysql(HttpServletRequest req) throws ServletException, IOException {
        //创建对象集合
        ArrayList<Student> Students = new ArrayList<Student>();

        //拿到数据
        Part filePart = req.getPart("excelFile");
        //获取输入流
        InputStream input = filePart.getInputStream();

        //对象获取完毕
        Students = ExcelServletUtil.excelForStudent(input, Students);

        //循环调用add函数 将每个Student对象作为参数依次传递
        for (Student stu : Students) {
            ss.addStudent(stu);
        }

        req.setAttribute("Students", Students);//写入请求头域
        return "index";//转发至展示界面

    }


    @RequestMapping(value = "/CaptchaService", method = RequestMethod.GET)
    public void CaptchaService(HttpServletResponse resp, HttpSession session) throws IOException {
        resp.setHeader("Content-Type", "image/jpeg");
        resp.setDateHeader("Expires", 0);
        resp.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
        resp.addHeader("Cache-Control", "post-check=0, pre-check=0");
        resp.setHeader("Pragma", "no-cache");
        try (OutputStream outputStream = resp.getOutputStream()) {
            byte[] captchaImageBytes = captchaService.generateCaptchaImage(session);
            outputStream.write(captchaImageBytes);
            outputStream.flush();
        }
        System.out.println("CaptchaService......");

    }

    @RequestMapping(value = "/Login")
    public String Login(HttpServletRequest req) throws IOException {
        req.setCharacterEncoding("utf-8");
        System.out.println(req);
        //获取前端用户输入数据
        String name = req.getParameter("username");
        String pwd = req.getParameter("password");
        String captcha = req.getParameter("captchaInput");
        System.out.println(name);
        System.out.println(pwd);
        System.out.println(captcha);

        if (!CaptchaUtil.verify(captcha, req)) {
            //将用户输入的用户名及密码保留
            req.setAttribute("name", name);
            req.setAttribute("password", pwd);
            System.out.println("验证码错误");
            req.setAttribute("Error", 0);//写入错误码调用前端弹窗函数
            //返回登陆界面
//            req.getRequestDispatcher("index.jsp").forward(req, resp);

            return "index";  // 结束方法的执行
        }
        //用户名非空判断
        if (name == null || name.isEmpty()) {
            System.out.println("用户名为空");
            //返回登陆界面
//            req.getRequestDispatcher("index.jsp").forward(req, resp);
            return "index";  // 结束方法的执行
        } else if (pwd == null || pwd.isEmpty()) {
            System.out.println("密码为空");
            //返回登陆界面
//            req.getRequestDispatcher("index.jsp").forward(req, resp);
            return "index";  // 结束方法的执行
        }

        //进行数据库比对
        if (rs.getHash("user:" + name) == null) {
            System.out.println("用户名错误");
            req.setAttribute("password", pwd);//保留密码
            req.setAttribute("Error", 1);//写入错误码调用前端弹窗函数
            //返回登陆界面
//            req.getRequestDispatcher("index.jsp").forward(req, resp);
            return "index";
            // 结束方法的执行
        } else if (!rs.getHashValue("user:" + name, "pwd").equals(getMD5Hash(pwd))) {
            System.out.println("密码错误");
            req.setAttribute("name", name);//保留用户名
            req.setAttribute("Error", 2);//写入错误码调用前端弹窗函数
            //返回登陆界面
//            req.getRequestDispatcher("index.jsp").forward(req, resp);
            return "index";// 结束方法的执行
        }

        System.out.println("登录成功");
        Map<String, Object> map =  rs.getHash("user:" + name);
        Student asd = new Student((String)map.get("id"),(String)map.get("name"),(String)map.get("sex"),(String)map.get("age"),(String)map.get("address"),(String)map.get("pwd"));
        req.setAttribute("student", asd);//获取用户对象写入请求头
        req.setAttribute("Students", ss.findAll());//获取全部用户对象写入请求头
        HttpSession s = req.getSession();//获取session对象
        s.setAttribute("login", true);//设置登录成功后在session中更改属性以便监听器监听
        s.setMaxInactiveInterval(10 * 60);//设置时间十分钟不活动自动销毁session,清除在线状态
//            req.getRequestDispatcher("excelShow.jsp").forward(req, resp);
        return "excelShow";
    }


    public static String getMD5Hash(String input) {
        try {
            // 获取MD5 MessageDigest实例
            MessageDigest md = MessageDigest.getInstance("MD5");

            // 更新要加密的数据
            md.update(input.getBytes());

            // 完成加密计算
            byte[] digest = md.digest();

            // 将加密后的字节转换为16进制字符串
            BigInteger number = new BigInteger(1, digest);
            String hashtext = number.toString(16);

            // 确保哈希长度为32个字符
            while (hashtext.length() < 32) {
                hashtext = "0" + hashtext;
            }
            return hashtext;

        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }


}
